/**
 * @Project Name:hoofungson-elk-log
 * @Package Name:cn.hoofungson.framework.elk.log.aspect
 * @Since JDK 1.8
 */

package cn.hoofungson.framework.elk.log.aspect;

import cn.hoofungson.framework.elk.log.annotation.LogServiceContext;
import cn.hoofungson.framework.elk.log.util.ThreadLocalUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @Description: 日志业务切面处理
 * @Author 胡松 hoofungson@163.com
 * @Date 2019-08-31 16:53
 * @Version V1.0
 */
@Order(1)
@Aspect
@Component
public class LogServiceContextAspect {

    @Pointcut("@annotation(cn.hoofungson.framework.elk.log.annotation.LogServiceContext)")
    public void logServiceContext() {
    }

    @Before("logServiceContext()")
    public void logServiceContextBefore(JoinPoint joinPoint) throws ClassNotFoundException {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] classes = method.getParameterTypes();
                if (classes.length == arguments.length) {
                    if (!method.isAnnotationPresent(LogServiceContext.class)) {
                        return;
                    }
                    ThreadLocalUtils.getLogServiceContextThreadLocal().set(method.getAnnotation(LogServiceContext.class));
                    break;
                }
            }
        }
    }
}
